<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <h2 class="login-title">欢迎登录</h2>
        <p class="login-subtitle">请输入您的账号和密码</p>
      </div>
      
      <el-form 
        :model="loginForm" 
        label-width="0"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名" 
            prefix-icon="el-icon-user"
            size="large"
            @blur="validateUsername"
          />
          <transition name="el-zoom-in-top">
            <span v-if="!isUsernameValid" class="error-message">
              {{ usernameErrorMessage }}
            </span>
          </transition>
        </el-form-item>

        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码" 
            prefix-icon="el-icon-lock"
            size="large"
            show-password
            @blur="validatePassword"
            @keyup.enter="handleLogin"
          />
          <transition name="el-zoom-in-top">
            <span v-if="!isPasswordValid" class="error-message">
              {{ passwordErrorMessage }}
            </span>
          </transition>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleLogin" 
            class="login-button"
            size="large"
            :loading="loading"
          >
            立即登录
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-footer">
        <el-link type="info">忘记密码</el-link>
        <el-link type="primary" @click="toRegister">注册账号</el-link>
      </div>
    </el-card>
    
    <div class="login-bg">
      <div class="bg-circle bg-circle-1"></div>
      <div class="bg-circle bg-circle-2"></div>
      <div class="bg-circle bg-circle-3"></div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const loading = ref(false)

// 登录表单数据
const loginForm = ref({
  username: 'admin',
  password: '123456'
})

// 用户名验证状态和错误信息
const isUsernameValid = ref(true)
const usernameErrorMessage = ref('')

// 密码验证状态和错误信息
const isPasswordValid = ref(true)
const passwordErrorMessage = ref('')

// 手动验证用户名
const validateUsername = () => {
  const { username } = loginForm.value
  if (!username) {
    isUsernameValid.value = false
    usernameErrorMessage.value = '请输入用户名'
  } else if (username.length < 3 || username.length > 20) {
    isUsernameValid.value = false
    usernameErrorMessage.value = '长度在 3 到 20 个字符'
  } else {
    isUsernameValid.value = true
    usernameErrorMessage.value = ''
  }
}

// 手动验证密码
const validatePassword = () => {
  const { password } = loginForm.value
  if (!password) {
    isPasswordValid.value = false
    passwordErrorMessage.value = '请输入密码'
  } else if (password.length < 6 || password.length > 20) {
    isPasswordValid.value = false
    passwordErrorMessage.value = '长度在 6 到 20 个字符'
  } else {
    isPasswordValid.value = true
    passwordErrorMessage.value = ''
  }
}

//跳转到注册页面
const toRegister = async () => {
  router.push("/register")
}

// 登录处理函数
const handleLogin = async () => {
  validateUsername()
  validatePassword()

  if (!isUsernameValid.value || !isPasswordValid.value) {
    return
  }

  loading.value = true
  try {
    const response = await axios.post('/api/auth/login', {
      username: loginForm.value.username,
      password: loginForm.value.password
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.data.code === 200) {
      ElMessage.success(response.data.message)
      // 从响应中提取行政编码
      const { role, token, username, parentCode } = response.data.data
      
      // 存储到localStorage
      localStorage.setItem('token', token)
      localStorage.setItem('role', role)
      localStorage.setItem('user', JSON.stringify({
        username: username,
        parentCode: parentCode // 新增行政编码
      }))
      
      // 或者使用Vuex存储（推荐）
      // store.commit('SET_USER_INFO', { username, role, parentCode })
      
      router.push('/home')
    } else {
      ElMessage.error(response.data.message || '登录失败')
    }
  } catch (error) {
    console.error('登录错误:', error)
    if (error.response) {
      if (error.response.status === 401) {
        ElMessage.error('用户名或密码错误')
      } else if (error.response.data && error.response.data.message) {
        ElMessage.error(error.response.data.message)
      } else {
        ElMessage.error(`请求错误: ${error.response.status}`)
      }
    } else if (error.request) {
      ElMessage.error('网络错误，请检查您的连接')
    } else {
      ElMessage.error('请求出错，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  position: relative;
  overflow: hidden;
}

.login-card {
  width: 420px;
  padding: 40px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
  z-index: 1;
  position: relative;
}

.login-header {
  text-align: center;
  margin-bottom: 36px;
}

.login-title {
  margin-bottom: 8px;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.login-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
  margin-top: 10px;
  letter-spacing: 2px;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
  display: block;
  line-height: 1;
}

.login-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.bg-circle {
  position: absolute;
  border-radius: 50%;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
}

.bg-circle-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  right: -100px;
}

.bg-circle-2 {
  width: 200px;
  height: 200px;
  bottom: -50px;
  left: -50px;
}

.bg-circle-3 {
  width: 150px;
  height: 150px;
  bottom: 100px;
  right: 100px;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-card {
    width: 90%;
    padding: 30px 20px;
  }
  
  .login-title {
    font-size: 20px;
  }
}
</style>